import threading
import time

def thread_safe_demo():
    print("=== 线程安全示例（加锁改造） ===")
    counter = 0
    thread_count = 5  # 线程数量
    iteration_count = 10000  # 每个线程的循环次数
    lock = threading.Lock()  # 创建锁对象

    def increment():
        nonlocal counter
        for _ in range(iteration_count):
            # 使用with语句自动获取和释放锁，确保操作原子性
            with lock:
                # 读取当前值
                current = counter
                # 即使有延迟，加锁后也不会发生线程切换导致的竞态条件
                time.sleep(0.000001)
                # 修改并写回
                current += 1
                counter = current

    # 创建并启动线程
    threads = []
    for _ in range(thread_count):
        t = threading.Thread(target=increment)
        threads.append(t)
        t.start()

    # 等待所有线程完成
    for t in threads:
        t.join()

    # 输出结果
    expected = thread_count * iteration_count
    print(f"期望结果: {expected}")
    print(f"实际结果: {counter}")
    print(f"偏差值: {expected - counter}\n")

if __name__ == "__main__":
    # 多次运行，观察结果一致性
    for i in range(3):
        print(f"第{i+1}次运行:")
        thread_safe_demo()
